package com.io;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Random;

public class WriteFile {

	static String filepath = ReadFile.class.getClassLoader().getResource("write.txt").getFile();

	// 1. 写入单个字节
	public static void writeFileAsByte() throws IOException {
		OutputStream os = null;
		try {
			os = new FileOutputStream(filepath);
			os.write('1');
			os.write('2');
			os.write('3');
			os.write('4');
			os.flush();// 把缓冲区内的数据刷新到磁盘

		} finally {
			if (os != null) {
				os.close();// 关闭流
			}
		}
	}

	// 2. 写入字节数组
	public static void writeFileAsByteArray() throws IOException {
		OutputStream os = null;
		try {
			os = new BufferedOutputStream(new FileOutputStream(filepath));
			// 模拟
			byte[] data = new byte[256];
			new Random().nextBytes(data);

			os.write(data);

		} finally {
			if (os != null) {
				os.close();// 关闭流
			}
		}
	}

	// 3. 写入单个字符
	public static void writeFileAsChar() throws IOException {
		Writer writer = null;
		try {
			writer = new FileWriter(filepath);
			// 模拟
			writer.write('1');
			writer.write('2');
			writer.write('3');
			writer.write('4');
			writer.flush();

		} finally {
			if (writer != null) {
				writer.close();// 关闭流
			}
		}
	}

	// 4. 写入字符数组
	public static void writeFileAsCharArray() throws IOException {
		Writer writer = null;
		try {
			writer = new FileWriter(filepath);
			// 模拟
			writer.write(new char[] { '1', '1', '1', '1' });
			writer.flush();
		} finally {
			if (writer != null) {
				writer.close();// 关闭流
			}
		}
	}

	public static void main(String[] args) throws IOException {
		// writeFileAsByte();
		writeFileAsByteArray();
		// writeFileAsChar();
		// writeFileAsCharArray();
	}

}
